import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0,
    // 任务列表
    list:[],
    // 文本框的输入内容
    inputValue:'123',
    // 前端模拟下一个ID
    nextId:5,
    viewKey:'all'
  },
  getters: {
    showNum (state) {
      return '当前最新的数量是【' + state.count + '】'
    },
    //统计未完成的条数
    unDoneLength(state){
      return state.list.filter(x =>x.done === false).length
    },
    infoList(state){
      if (state.viewKey==='all') {
        return state.list
      }
      if (state.viewKey==='undoen'){
        return state.list.filter(x => !x.done)
      }
      if (state.viewKey==='done'){
        return state.list.filter(x => x.done)
      }
      return state.list
    }
  },
  // vuex的方法
  mutations: {
    add (state) {
      state.count++
    },
    addN (state, step) {
      state.count += step
    },
    sub (state) {
      state.count--
    },
    subN (state, step) {
      state.count -= step
    },
    initList(state,list){
      state.list = list
    },
    setInputValue(state,val){
      state.inputValue = val
    },
    addItem(state){
      const obj ={
        id:state.nextId,
        info:state.inputValue.trim(),
        done:false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue=''
    },
    removeItem(state,id){
      const i = state.list.findIndex(x =>x.id===id)
      if (i!==-1) {
        state.list.splice(i,1)
      }
    },
    changeStatus(state,param){
      const i = state.list.findIndex(x =>x.id=== param.id)
      if (i!==-1) {
        state.list[i].done = param.status
      }
    },
    cleanDone(state){
      state.list = state.list.filter(x => x.done ===false)
    },
    changeViewKey(state,key){
      state.viewKey = key
    }

  },
  // vuex异步操作
  actions: {
    addAsYnc (context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000)
    },
    addNAsYnc (context, step) {
      setTimeout(() => {
        context.commit('addN', step)
      }, 2000)
    },
    subAsync (context) {
      setTimeout(() => {
        context.commit('sub')
      }, 1000)
    },
    subNAsync (context, step) {
      setTimeout(() => {
        context.commit('subN', step)
      }, 1000)
    },
    getList(context){
      axios.get('./list.json').then(({data})=>{
        console.log(data);
        context.commit('initList',data)
      })
    }
  },
  modules: {
  }
})
